package com.android.task6;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

/**
 * Class for handling the contact request operation.
 */
public class BluetoothClient {

    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
   
    BluetoothAdapter bluetoothAdapter;
    BluetoothDevice bluetoothDevice;
    ContactManager contactManager;
    String macAddress;
    
    public BluetoothClient(BluetoothAdapter bluetoothAdapter,ContactManager contactManager, String macAddress){
    	
    	this.bluetoothAdapter = bluetoothAdapter;
    	this.contactManager = contactManager;
    	this.macAddress = macAddress;
    	this.bluetoothDevice = this.bluetoothAdapter.getRemoteDevice(this.macAddress);
    	
    	new Thread(new clientThread(this.bluetoothAdapter,this.bluetoothDevice,this.contactManager)).start();
    	
    }
    
    private class clientThread implements Runnable{

    	BluetoothAdapter bluetoothAdapter;
    	BluetoothDevice bluetoothDevice;
    	ContactManager contactManager;
    	
    	OutputStream outputStream;
    	ObjectInputStream inputStream;
    	
    	public clientThread(BluetoothAdapter bluetoothAdapter,BluetoothDevice bluetoothDevice,ContactManager contactManager){
    		this.bluetoothAdapter = bluetoothAdapter;
    		this.bluetoothDevice = bluetoothDevice;
    		this.contactManager = contactManager;
    	}
    	
		@Override
		public void run() {
			
			BluetoothSocket clientSocket;
			
			try {
				Log.i("bt","getting clientSocket");
				clientSocket = this.bluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID);
				
				this.bluetoothAdapter.cancelDiscovery();
				Log.i("bt","connects to server");
				clientSocket.connect();
				Log.i("bt","gets outputStream");
				outputStream = clientSocket.getOutputStream();
				Log.i("bt","writes a byte");
				outputStream.write(1);
				Log.i("bt","gets the inputstream");
				inputStream = new ObjectInputStream(clientSocket.getInputStream());
				Log.i("bt","creates object");
				Object receivedObject = null;
				Log.i("bt","waits for object");
				while((receivedObject = inputStream.readObject()) != null){
					Log.i("bt","object received");
					if(receivedObject instanceof Contact){
						Log.i("bt","object was a contact, writes");
						this.contactManager.writeContact((Contact) receivedObject);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
    };
}
